package com.yoga.db;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import test.java.Test;

/**
 * 使用MyBatis框架进行数据库操作，该类用来建立连接，用单例模式维护一个连接的Session
 *
 */
public class DbBuilder {

	private static DbBuilder dbHelper = null;
	private SqlSession session = null;

	private DbBuilder() {
		initDb();
	}

	public static DbBuilder getInstance() {
		if (dbHelper == null) {
			dbHelper = new DbBuilder();
		}
		return dbHelper;
	}

	public void initDb() {
		if (session == null) {
			// mybatis的配置文件
			String resource = "conf.xml";
			// 使用类加载器加载mybatis的配置文件（它也加载关联的映射文件）
			InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
			// 构建sqlSession的工厂
			SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
			// 创建能执行映射文件中sql的sqlSession
			session = sessionFactory.openSession();
		}
	}

	public SqlSession getSession() {
		return session;
	}	
}
